package com.aizuda.boot.config;

import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.security.token.SSOToken;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * 方法阻断拦截器，禁止演示非法操作
 *
 * @author jobob
 * @since 2022-01-03
 */
public class BlockHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (Objects.equals("OPTIONS", request.getMethod())) {
            return true;
        }
        SSOToken ssoToken = SSOHelper.getSSOToken(request);
        if (null != ssoToken && Objects.equals("1", ssoToken.getId())) {
            return true;
        }
        String uri = request.getRequestURI();
        if (uri.contains("/create") || uri.contains("/update") || uri.contains("/delete")
                || uri.contains("/status/") || uri.contains("/reset-password")
                || uri.contains("/v1/process/delete")) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write("{\"code\": -1,\"message\": \"Access forbidden in demo environment\"}");
            return false;
        }
        return true;
    }
}
